package com.ss.android.caijing.stepcounterlib.core;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
import android.os.Build;
import android.support.annotation.RequiresApi;

import com.ss.android.caijing.stepcounterlib.callback.StepCallBack;
import com.ss.android.caijing.stepcounterlib.log.CodeLog;
import com.ss.android.caijing.stepcounterlib.log.SSLog;

import static android.hardware.SensorManager.SENSOR_STATUS_ACCURACY_LOW;

/**
 * Created by base on 2016/8/17.
 */
public class StepInPedometer extends StepMode {
    private final String TAG = "StepInPedometer";
    private int liveStep = 0;

    public StepInPedometer(Context context, StepCallBack stepCallBack) {
        super(context, stepCallBack);

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void registerSensor() {
        addCountStepListener();
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        liveStep = (int) event.values[0];
        if (event.accuracy == SENSOR_STATUS_ACCURACY_LOW){
            return;
        }
        StepMode.CURRENT_SETP += liveStep;
        CodeLog.i("StepInPedometer", "stepadd:" + StepMode.CURRENT_SETP);
        stepCallBack.Step(StepMode.CURRENT_SETP);

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void addCountStepListener() {
        Sensor detectorSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
        if (detectorSensor != null) {
            sensorManager.registerListener(this, detectorSensor, SensorManager.SENSOR_DELAY_UI);
            isAvailable = true;
        } else {
            isAvailable = false;
            SSLog.v(TAG, "Count sensor not available!");
        }
    }
}
